package com.iotek.bookstore.modle.dao.impl;

import com.iotek.bookstore.modle.entity.Order;
import com.iotek.bookstore.util.PreparedStatementSetter;
import com.iotek.bookstore.util.RsCallBackHandler;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class OrderDaoImpl extends MyBookstoreDaoImpl<Order> {

    /*
    * 添加订单信息
    * */
    @Override
    public int insert(final Order order) {
        String sql="insert into orders(orderId,userId,addressId,totalPrice) values(?,?,?,?)";
        return this.update(sql, new PreparedStatementSetter() {
            public void setValues(PreparedStatement pstmt) throws SQLException {
                pstmt.setLong(1,order.getId());
                pstmt.setInt(2,order.getUserId());
                pstmt.setLong(3,order.getAddressId());
                pstmt.setDouble(4,order.getPrice());
            }
        });
    }

    /*
    * 查询所有的用户订单信息
    * */
    @Override
    public List<Order> queryAll() {
        String sql="select * from orders";
        this.query(sql, null, new RsCallBackHandler() {
            public void processRs(ResultSet rs) throws SQLException {
                createOrder(rs);
            }
        });
        return list;
    }


    /*
    * 根据用户ID查询该用户的所有订单信息
    * */
    @Override
    public List<Order> query(final int id) {
        String slq="select * from orders where userId=?";
        this.query(slq, new PreparedStatementSetter() {
            public void setValues(PreparedStatement pstmt) throws SQLException {
                pstmt.setInt(1, id);
            }
        }, new RsCallBackHandler() {
            public void processRs(ResultSet rs) throws SQLException {
                createOrder(rs);
            }
        });
        return list;
    }

    /*
    * 生成查询通用的Order实例
    * */
    private void createOrder(ResultSet rs)throws SQLException {
        while (rs.next()){
            Order order=new Order();
            order.setId(rs.getLong(1));
            order.setUserId(rs.getInt(2));
            order.setAddressId(rs.getLong(3));
            order.setPrice(rs.getDouble(4));
            list.add(order);
        }
    }
}
